package com.yehun.web.controller;

import com.yehun.entity.PagerEntity;
import com.yehun.entity.Test;
import com.yehun.enums.ResultEnum;
import com.yehun.enums.StatusEnum;
import com.yehun.exception.CustomException;
import com.yehun.exception.NotFoundException;
import com.yehun.service.TestService;
import com.yehun.utils.EnumUtils;
import com.yehun.utils.JsonUtils;
import com.yehun.utils.ParamUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.LinkedList;
import java.util.List;

@Controller
@RequestMapping(value = "test")
public class TestController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(TestController.class);

    private final TestService testService;

    @Autowired
    public TestController(TestService testService) {
        this.testService = testService;
    }

    @RequestMapping(value = { "", "list" })
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("test/index");
        int pageIndex = ParamUtils.getPageIndex("pageIndex");
        int pageSize = ParamUtils.getPageSize("pageSize", 10);
        logger.info("TestController.index, pageIndex={}", pageIndex);
        PagerEntity<Test> pager = testService.list(pageIndex, pageSize);
        logger.info("TestController.index, total={}", pager.getTotal());
        logger.info("TestController.index, size={}", pager.getData().size());
        logger.info("TestController.index, pageNum={}", pager.getPageNum());
        view.addObject("pager", pager);
        logger.info("TestController.index, list={}", JsonUtils.serialize(pager.getData()));
        return view;
    }


    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add() {
        logger.info("TestController.add, begin...");
        ModelAndView view = new ModelAndView("test/add");
        view.addObject("test", new Test());
        view.addObject("statusList", EnumUtils.getSelect(StatusEnum.class));
        logger.info("TestController.add, end...");
        return view;
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ModelAndView addPost(@Valid @ModelAttribute("test") Test test, BindingResult bindingResult) throws CustomException {
        logger.info("TestController.add, begin...");
        ModelAndView view = new ModelAndView("test/add");
        if (test == null) {
            throw new CustomException(ResultEnum.NotFoundData, "未找到提交数据");
        }
        view.addObject("statusList", EnumUtils.getSelect(StatusEnum.class, test.getStatus()));
        if (!bindingResult.hasErrors()) {
            int row = testService.save(test);
            logger.info("TestController.add, row={}", row);
            view.addObject("message", "success");
        }
        logger.info("TestController.add, end...");
        return view;
    }

    @RequestMapping(value = "edit/{id:\\d+}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") int id) throws NotFoundException {
        logger.info("TestController.edit, id={}", id);
        ModelAndView view = new ModelAndView("test/edit");
        Test test = testService.get(id);
        if (test == null) {
            throw new NotFoundException(ResultEnum.NotFoundData);
        }
        view.addObject("test", test);
        view.addObject("statusList", EnumUtils.getSelect(StatusEnum.class, test.getStatus()));
        return view;
    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.POST)
    public ModelAndView editPost(@Valid @ModelAttribute("test") Test test, BindingResult bindingResult) {
        ModelAndView view = new ModelAndView("test/edit");
        view.addObject("test", test);
        view.addObject("statusList", EnumUtils.getSelect(StatusEnum.class, test.getStatus()));
        if (!bindingResult.hasErrors()) {
            int row = testService.update(test);
            logger.info("TestController.edit, row＝{}", row);
            view.addObject("message", "success");
        } else {
            List<ObjectError> errors = bindingResult.getAllErrors();
            if (errors != null && !errors.isEmpty()) {
                List<String> listError = new LinkedList<>();
                for (ObjectError error : errors) {
                    logger.error("TestController.edit, field={},error={}", error.getCode(), error.getDefaultMessage());
                    listError.add(error.getDefaultMessage());
                }
                view.addObject("listError", listError);
            }
        }
        return view;
    }

    @RequestMapping(value = "remove/{id}")
    public String remove(@PathVariable(value = "id") int id) {
        logger.info("TestController.remove, begin...");
        logger.info("TestController.remove, id={}", id);
        Test test = testService.get(id);
        if (test != null) {
            int row = testService.remove(id);
            logger.info("TestController.remove, row={}", row);
        } else {
            logger.info("TestController.remove, 未找到test");
        }
        logger.info("TestController.remove, end...");
        return "redirect:/test";
    }

}
